<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="disabled">
      <a-form-model layout="horizontal" ref="subForm" slot="detail" :model="model" :rules="validatorRules" v-bind="formItemLayout">
        <z-form-item :datas="fieldArr" :form="model" :rules="validatorRules" :gutter="0" @change="getChange" @rows="getRows" />
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { outLeaveApply } from '@/api/sjsk/personService'
  export default {
    props: {
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model: {},
        confirmLoading: false,
        formItemLayout: {
          labelCol: { span: 6 },
          wrapperCol: { span: 16 }
        },
        fieldArr: [
          {label: '姓名', prop: 'name', tagType: 'input', disabled: true},
          {label: '性别', prop: 'sex', tagType: 'dict-select', dictCode:'sex', disabled: true},
          {label: '类型', prop: 'sjskType', tagType: 'dict-select', dictCode:'risk_level_person_type', disabled: true},
          {label: '执行时间', prop: 'executeTime', tagType: 'input', disabled: true},
          {label: '身份证号', prop: 'identityCard', tagType: 'input', disabled: true},
          {label: '联系电话', prop: 'phone', tagType: 'input', disabled: true},
          {label: '户籍地详址', prop: 'householdAddress', tagType: 'input', disabled: true},
          {label: '居住地详址', prop: 'currentAddress', tagType: 'input', disabled: true},
          {label: '工作单位', prop: 'workUnit', tagType: 'input', disabled: true},
          {label: '活动范围', prop: 'activityScopes', tagType: 'linkage-area'},
          {label: '请假开始时间', prop: 'startDate', tagType: 'date-picker', format: 'YYYY-MM-DD'},
          {label: '请假结束时间', prop: 'endDate', tagType: 'date-picker', format: 'YYYY-MM-DD'},
          {label: '请假时长', prop: 'outDay', tagType: 'input', disabled: true},
          {label: '请假事由', prop: 'outReason', tagType: 'textarea',},
          {label: '证明材料', prop: 'file', tagType: 'upload-file', fileDescribe: '可上传多个附件'},
        ],
        validatorRules: {
          activityScopes:[ { required: true, type: 'array', message: '请选择活动范围' }],
          startDate:[ { required: true, message: '请选择请假开始时间' }],
          endDate:[ { required: true, message: '请选择请假结束时间' }],
          outReason:[ { required: true, message: '请输入请假事由!' },]
        }
      }
    },
    methods: {
      show (record) {
        // this.model = record?Object.assign({}, record):this.model;
        this.$set( this.model, 'sjskPersonId', record.id )
        this.$set( this.model, 'name', record.realName )
        this.$set( this.model, 'sex', record.sex )
        this.$set( this.model, 'sjskType', record.sjskType )
        this.$set( this.model, 'executeTime', record.sjskStartDate + '~' + record.sjskEndDate )
        this.$set( this.model, 'identityCard', record.identityCard )
        this.$set( this.model, 'phone', record.phone )
        this.$set( this.model, 'householdAddress', record.householdAddress )
        this.$set( this.model, 'currentAddress', record.currentAddress )
        this.$set( this.model, 'workUnit', record.workUnit )
      },
      submitForm () {
        const parameter = Object.assign({}, this.model)
        this.$refs.subForm.validate((valid)=> {
          console.log(parameter)
          if (valid) {
            outLeaveApply(parameter)
              .then(res => {
                this.confirmLoading = false
                if (res.success) {
                  this.$message.success(res.message)
                  this.$emit('ok');
                } else {
                  this.$message.warn(res.message)
                }
              })
              .catch(e => {
                this.$message.warn('请求失败！')
                this.confirmLoading = false
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      getRows(prop, value) {
        if(prop==='activityScopes') {
          let data = value?value.map(v=>v.title): []
          this.$set(this.model, 'activityScope', data.toString())
        }
      },
      getChange(prop, value) {
        if(prop==='activityScopes') {
          let data = value && Array.isArray(value)? value.filter(item=>{ return item }): []
          this.$set(this.model, 'activityScopeLevel', data.toString())
        }
        if(prop==='startDate') {
          this.onDateChangeNew(1, ['startDate', 'endDate'], ['请假开始时间','请假结束时间'])
        }
        if(prop==='endDate') {
          this.onDateChangeNew(2, ['startDate', 'endDate'], ['请假开始时间','请假结束时间'])
        }
      },
      // 两时间校验
      onDateChangeNew(val, time, message) {
        if(!val&&!time&&!message) return
        let startTime = time[0]
        let endTime = time[1]
        let startMessage= message[0]
        let endMessage= message[1]
        let flag = this.dateCompare(this.model[startTime], this.model[endTime])
        if (flag && this.model[startTime]!==this.model[endTime]) {
          if (val == 1) {
            // this.$refs['subForm'].validateField('startDate')
            this.$message.warning(startMessage+"等于不能小于"+endMessage)
            this.$set( this.model, startTime, '')
          } else {
            // this.$refs['subForm'].validateField('endDate')
            this.$message.warning(endMessage+"必须大于或等于"+startMessage)
            this.$set( this.model, endTime, '')
          }
        }
        // 外出请假记录---计算外出天数
        if(this.model.startDate && this.model.endDate) {
          this.$set( this.model, 'outDay', this.getDaysBetween(this.model.startDate, this.model.endDate))
        } else {
          this.$set( this.model, 'outDay', '')
        }
      },
      //比较两个日期大小
      dateCompare(startDate, endDate) {
        if (
          startDate == "" ||
          endDate == "" ||
          startDate == undefined ||
          endDate == undefined ||
          startDate == null ||
          endDate == null
        )
          return;
        const aStart = startDate.split("-"); //转成成数组，分别为年，月，日，下同
        const aEnd = endDate.split("-");
        const startDateTemp = aStart[0] + "/" + aStart[1] + "/" + aStart[2];
        const endDateTemp = aEnd[0] + "/" + aEnd[1] + "/" + aEnd[2];
        if (startDateTemp >= endDateTemp) return true;
        else return false;
      },
      /**
       * 计算两个日期之间的天数
       * @param dateString1  开始日期 yyyy-MM-dd
       * @param dateString2  结束日期 yyyy-MM-dd
       * @returns {number} 如果日期相同 返回一天 开始日期大于结束日期，返回0
       */
      getDaysBetween(dateString1, dateString2) {
        const startDate = Date.parse(dateString1);
        const endDate = Date.parse(dateString2);
        if (startDate>endDate){
            return 0;
        }
        if (startDate==endDate){
            return 1;
        }
        const days=(endDate - startDate)/(1*24*60*60*1000);
        return  days;
      }
    }
  }
</script>
